#将json文件提取出文字，并写入到csv文件中
import json
import locale
import csv
import os
import re
def find_json_files(directory):
    print(directory)
    pdf_files = []  # 存储找到的PDF文件的绝对路径
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith('.json'):  # 检查文件后缀是否为.pdf
                pdf_files.append(os.path.join(root, file))  # 添加文件的绝对路径
    return pdf_files


def parse_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        json_data = file.read() 
        data = json.loads(json_data)
# 访问第一页的文本内容
        first_page_text = data["page_0"]["text"]
# 定义要查找的标识
        pattern = r"N-20221101.*"
        match = re.search(pattern, first_page_text)  
        print(match.group())
        return match.group()
       
         

# 使用示例,注意文件目录的写法，使用双反斜杠不行
directory_path = (r'C:\Users\awu\projects\tencent-ocr-analysis-master\mupdf_json')
input_json_list =find_json_files(directory_path)
#写入到csv文件
csv_list=[]
for input_json in input_json_list:
    file_name =os.path.splitext(os.path.basename(input_json))[0]
    print(input_json )
    data=[]
    data.append(parse_json_file(input_json))
    data.insert(0,file_name)
    print(data)
    csv_list.append(data)
    print(csv_list)
    print(csv_list)

# 必须是列表加列表，每个列表为一行
with open(r'C:\Users\awu\projects\tencent-ocr-analysis-master\mupdf2sn.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(csv_list)

